<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <!-- 搜索表单内容保持不变 -->
      <el-form-item label="航机员" prop="flightCrew">
        <el-input
          v-model="queryParams.flightCrew"
          placeholder="请输入航机员"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="进港航班" prop="inboundFlight">
        <el-input
          v-model="queryParams.inboundFlight"
          placeholder="请输入进港航班"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="进港时间" prop="inboundTime">
        <el-time-picker
          v-model="queryParams.inboundTime"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="选择进港时间"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="预落时间" prop="preLandingTime">
        <el-time-picker
          v-model="queryParams.preLandingTime"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="选择预落时间"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="起飞时间" prop="depTime">
        <el-time-picker
          v-model="queryParams.depTime"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="选择起飞时间"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="航班号" prop="flightNo">
        <el-input
          v-model="queryParams.flightNo"
          placeholder="请输入航班号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机号" prop="machineNo">
        <el-input
          v-model="queryParams.machineNo"
          placeholder="请输入机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="记录日期" prop="recordDate">
        <el-date-picker
          v-model="queryParams.recordDate"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="选择记录日期"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 获取最新
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleSyncQuarter"
          v-hasPermi="['distm:schedule-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 同步季度计划
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['distm:schedule-record:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :row-class-name="tableRowClassName">
      <!-- 车辆信息列 -->
      <el-table-column
        v-if="columnVisibility.carInfo"
        label="车辆信息"
        align="center"
        prop="carInfo"
        min-width="140"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row.carInfo"
            placeholder="请输入车辆信息"
            clearable
            class="!w-120px"
            @blur="handleFieldChange(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 航机员列 -->
      <el-table-column
        v-if="columnVisibility.flightCrew"
        label="航机员"
        align="center"
        prop="flightCrew"
        min-width="180"
      >
        <template #default="scope">
          <el-select
            v-model="scope.row.flightCrew"
            placeholder="请选择航机员"
            class="!w-160px"
            @change="handleFieldChange(scope.row)"
          >
            <el-option
              v-for="item in userList"
              :key="item.shiftRecordIds"
              :label="item.shiftRecordNames"
              :value="item.shiftRecordIds"
            />
          </el-select>
        </template>
      </el-table-column>

      <!-- 进港航班列 -->
      <el-table-column
        v-if="columnVisibility.inboundFlight"
        label="进港航班"
        align="center"
        prop="inboundFlight"
        min-width="140"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row.inboundFlight"
            placeholder="请输入进港航班"
            clearable
            class="!w-120px"
            @blur="handleFieldChange(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 航班号列 -->
      <el-table-column
        v-if="columnVisibility.flightNo"
        label="航班号"
        align="center"
        prop="flightNo"
      />

      <!-- 机号列 -->
      <el-table-column
        v-if="columnVisibility.machineNo"
        label="机号"
        align="center"
        prop="machineNo"
        min-width="120"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row.machineNo"
            placeholder="请输入机号"
            clearable
            class="!w-100px"
            @blur="handleFieldChange(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 进港时间列 -->
      <el-table-column
        v-if="columnVisibility.inboundTime"
        label="进港时间"
        align="center"
        prop="inboundTime"
        min-width="140"
      >
        <template #default="scope">
          <el-time-picker
            v-model="scope.row.inboundTime"
            format="HH:mm"
            value-format="HH:mm"
            placeholder="选择进港时间"
            clearable
            class="!w-120px"
            @change="handleFieldChange(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 预落时间列 -->
      <el-table-column
        v-if="columnVisibility.preLandingTime"
        label="预落时间"
        align="center"
        prop="preLandingTime"
        min-width="140"
      >
        <template #default="scope">
          <el-time-picker
            v-model="scope.row.preLandingTime"
            format="HH:mm"
            value-format="HH:mm"
            placeholder="选择预落时间"
            clearable
            class="!w-120px"
            @change="handleFieldChange(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 机位列 -->
      <el-table-column
        v-if="columnVisibility.airportStands"
        label="机位"
        align="center"
        prop="airportStands"
        min-width="120"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row.airportStands"
            placeholder="请输入机位"
            clearable
            class="!w-100px"
            @blur="handleFieldChange(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 起飞时间列 -->
      <el-table-column
        v-if="columnVisibility.depTime"
        label="起飞时间"
        align="center"
        prop="depTime"
      />

      <!-- 备注列 -->
      <el-table-column
        v-if="columnVisibility.remarks"
        label="备注"
        align="center"
        prop="remarks"
        min-width="120"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row.remarks"
            placeholder="请输入备注"
            clearable
            class="!w-100px"
            @blur="handleFieldChange(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 商务舱数量列 -->
      <el-table-column
        v-if="columnVisibility.bussClassQty"
        label="商务舱数量"
        align="center"
        prop="bussClassQty"
        min-width="120"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row.bussClassQty"
            placeholder="请输入商务舱数量"
            clearable
            class="!w-100px"
            @blur="handleFieldChange(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 高级经济舱数量列 -->
      <el-table-column
        v-if="columnVisibility.premEcoClassQty"
        label="高级经济舱数量"
        align="center"
        prop="premEcoClassQty"
        min-width="125"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row.premEcoClassQty"
            placeholder="请输入高级经济舱数量"
            clearable
            class="!w-105px"
            @blur="handleFieldChange(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 经济舱数量列 -->
      <el-table-column
        v-if="columnVisibility.ecoClassQty"
        label="经济舱数量"
        align="center"
        prop="ecoClassQty"
        min-width="120"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row.ecoClassQty"
            placeholder="请输入经济舱数量"
            clearable
            class="!w-100px"
            @blur="handleFieldChange(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 特殊说明列 -->
      <el-table-column
        v-if="columnVisibility.specialRemarks"
        label="特殊说明"
        align="center"
        prop="specialRemarks"
        min-width="120"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row.specialRemarks"
            placeholder="请输入特殊说明"
            clearable
            class="!w-100px"
            @blur="handleFieldChange(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 机型列 -->
      <el-table-column
        v-if="columnVisibility.aircraftType"
        label="机型"
        align="center"
        prop="aircraftType"
      />

      <!-- 所属公司列 -->
      <el-table-column
        v-if="columnVisibility.airlineComp"
        label="所属公司"
        align="center"
        prop="airlineComp"
      />

      <!-- 日期列 -->
      <el-table-column
        v-if="columnVisibility.recordDate"
        label="日期"
        align="center"
        prop="recordDate"
        min-width="120"
      />

      <!-- 创建时间列 -->
      <el-table-column
        v-if="columnVisibility.createTime"
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />

      <!-- 生产状态列 -->
      <el-table-column
        v-if="columnVisibility.pstatus"
        label="生产状态"
        align="center"
        min-width="100px"
      >
        <template #default="scope">
          <el-tag type="primary"> {{ getStatusLabel(scope.row.pstatus) }}</el-tag>
        </template>
      </el-table-column>

      <!-- 操作列（始终显示） -->
      <el-table-column label="操作" align="center" min-width="200px" fixed="right">
        <template #header>
          <div
            @click="openColumnSetting"
            style="
              display: flex;
              align-items: center;
              justify-content: center;
              cursor: pointer;
              color: #43a2ff;
            "
          >
            <Icon icon="ep:setting" class="mr-5px" /> 操作
          </div>
        </template>
        <template #default="scope">
          <div class="flex items-center justify-center">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.flightNo)"
              v-hasPermi="['pplan:produce-record:update']"
            >
              查看详情
            </el-button>
            <el-button
              link
              type="primary"
              @click="openAddForm(scope.row.flightNo, scope.row.recordDate)"
            >
              加餐
            </el-button>
            <el-dropdown>
              <el-button type="primary" link><Icon icon="ep:d-arrow-right" /> 更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="item in pstatusList"
                    :key="item.value"
                    @click="handleStatusChange(scope.row, item.value)"
                    >{{ item.label }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 列设置弹窗 -->
  <el-dialog
    title="表格列设置"
    v-model="columnSettingVisible"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-checkbox-group v-model="selectedColumns" class="column-setting-group">
      <el-checkbox
        v-for="column in tableColumns"
        :key="column.prop"
        :label="column.prop"
        style="width: 25%"
      >
        {{ column.label }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="columnSettingVisible = false">取消</el-button>
      <el-button type="primary" @click="saveColumnSettings">确定</el-button>
    </template>
  </el-dialog>

  <!-- 其他弹窗组件保持不变 -->
  <FlightLogImportForm ref="importFormRef" @success="getList" />
  <ProduceRecordForm ref="formRef" @success="getList" />
  <ScheduleRecordAddForm ref="formAddRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { ScheduleRecordApi, ScheduleRecordVO } from '@/api/distm/schedule'
import FlightLogImportForm from './FlightLogImportForm.vue'
import { ShiftRecordApi } from '@/api/pplan/shiftrecord'
import ProduceRecordForm from '@/views/pplan/producerecord/ProduceRecordForm.vue'
import ScheduleRecordAddForm from '@/views/distm/schedule/ScheduleRecordAddForm.vue'

/** 配送管理-调度生产记录 列表 */
defineOptions({ name: 'ScheduleRecord' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ScheduleRecordVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  flightNo: undefined,
  depTime: undefined,
  flightCrew: undefined,
  inboundFlight: undefined,
  machineNo: undefined,
  inboundTime: undefined,
  preLandingTime: undefined,
  recordDate: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 生产状态 */
const pstatusList = reactive([
  { value: 1, label: '餐食准备完成' },
  { value: 2, label: '机供品准备完成' },
  { value: 3, label: '任务分配完成' },
  { value: 4, label: '航机任务确认' },
  { value: 5, label: '装机' },
  { value: 6, label: '完成' },
  { value: 7, label: '发车确认' },
  { value: 8, label: '进入机坪' },
  { value: 9, label: '到达机位完成' },
  { value: 10, label: '开始保障' },
  { value: 11, label: '结束保障' },
  { value: 12, label: '起飞' },
  { value: 13, label: '取消装机' },
  { value: 14, label: '取消完成' }
])

/** 计算生产状态 */
const getStatusLabel = (statusValue: number | string | undefined | null) => {
  if (!statusValue && statusValue !== 0) {
    return '未开始'
  }
  const numStatus = Number(statusValue)
  const matchedStatus = pstatusList.find((item) => item.value === numStatus)
  return matchedStatus ? matchedStatus.label : '未开始'
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ScheduleRecordApi.getScheduleRecordPage(queryParams)
    list.value = data.list
    list.value.forEach((item) => {
      item.inboundTime = item.inboundTime ? formatTimeArray(item.inboundTime) : ''
      item.preLandingTime = item.preLandingTime ? formatTimeArray(item.preLandingTime) : ''
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 工具函数：将 [小时, 分钟] 数组转换为 "HH:mm" 字符串
const formatTimeArray = (timeArray) => {
  if (!timeArray || timeArray.length !== 2) return null // 异常处理
  const hour = String(timeArray[0]).padStart(2, '0') // 补零（如 9 → "09"）
  const minute = String(timeArray[1]).padStart(2, '0') // 如 5 → "05"
  return `${hour}:${minute}`
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, flightNo?: string) => {
  formRef.value.openFlightNo(type, flightNo)
}

/** 加餐操作 */
const formAddRef = ref()
const openAddForm = (flightNo?: string, recordDate?: string) => {
  formAddRef.value.openAdd('create', flightNo, recordDate)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ScheduleRecordApi.deleteScheduleRecord(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ScheduleRecordApi.exportScheduleRecord(queryParams)
    download.excel(data, '配送管理-调度生产记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 同步季度计划 */
const handleSyncQuarter = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm('是否同步季度计划')
    // 发起导出
    exportLoading.value = true
    await ScheduleRecordApi.syncQuarterPlan()
    message.success('同步季度计划成功')
    // 刷新列表
    await getList()
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 查询用户精简列表 */
const userList = ref([])
const getUserList = async () => {
  try {
    const shiftDate = formatDate(new Date(), 'YYYY-MM-DD')
    const data = await ShiftRecordApi.getShiftRecordSimple(shiftDate)
    userList.value = data
  } catch (err) {
    console.error('获取用户列表失败:', err)
  }
}

const simpleFormData = reactive({
  id: undefined,
  flightNo: undefined,
  flightCrew: undefined
})

/** 处理用户选择变化 */
const handleUserChange = (id: number, flightNo: string, value: any) => {
  // 调用更新方法
  simpleFormData.id = id
  simpleFormData.flightNo = flightNo
  simpleFormData.flightCrew = value
  const data = simpleFormData as unknown as ScheduleRecordVO
  ScheduleRecordApi.updateScheduleRecord(data)
}

const handleFieldChange = async (row: ScheduleRecordVO) => {
  try {
    // （可选）数据预处理：确保数字字段类型正确（避免后端接收字符串）
    const updateData = {
      ...row,
      bussClassQty: row.bussClassQty ? Number(row.bussClassQty) : undefined,
      premEcoClassQty: row.premEcoClassQty ? Number(row.premEcoClassQty) : undefined,
      ecoClassQty: row.ecoClassQty ? Number(row.ecoClassQty) : undefined
    } as ScheduleRecordVO

    // 调用后端更新接口（用当前行的完整数据，含主键id）
    await ScheduleRecordApi.updateScheduleRecord(updateData)
    message.success(t('common.updateSuccess')) // 更新成功提示
  } catch (err) {
    message.error(t('common.updateFail')) // 更新失败提示
    console.error('字段更新失败:', err)
    // （可选）失败后回滚数据（重新拉取列表）
    await getList()
  }
}

/** 修改状态 */
const handleStatusChange = async (row: ScheduleRecordVO, newStatus: number) => {
  try {
    const updateData = {
      id: row.id,
      pstatus: newStatus
    } as Partial<ScheduleRecordVO>
    await ScheduleRecordApi.updateScheduleRecord(updateData)
    row.pstatus = newStatus
    message.success(t('common.updateSuccess'))
  } catch (err) {
    message.error(t('common.updateFail'))
    console.error('生产状态更新失败：', err)
  }
}

/** 用户导入 */
const importFormRef = ref()
const handleImportLog = () => {
  importFormRef.value.open()
}

/** 表格列配置相关逻辑 **/
// 定义所有表格列
const tableColumns = [
  { prop: 'carInfo', label: '车辆信息' },
  { prop: 'flightCrew', label: '航机员' },
  { prop: 'inboundFlight', label: '进港航班' },
  { prop: 'flightNo', label: '航班号' },
  { prop: 'machineNo', label: '机号' },
  { prop: 'inboundTime', label: '进港时间' },
  { prop: 'preLandingTime', label: '预落时间' },
  { prop: 'airportStands', label: '机位' },
  { prop: 'depTime', label: '起飞时间' },
  { prop: 'remarks', label: '备注' },
  { prop: 'bussClassQty', label: '商务舱数量' },
  { prop: 'premEcoClassQty', label: '高级经济舱数量' },
  { prop: 'ecoClassQty', label: '经济舱数量' },
  { prop: 'specialRemarks', label: '特殊说明' },
  { prop: 'aircraftType', label: '机型' },
  { prop: 'airlineComp', label: '所属公司' },
  { prop: 'recordDate', label: '日期' },
  { prop: 'createTime', label: '创建时间' },
  { prop: 'pstatus', label: '生产状态' }
]

// 控制列显示的变量
const columnVisibility = ref({})
// 选中的列（用于多选框组）
const selectedColumns = ref<string[]>([])
// 列设置弹窗显示状态
const columnSettingVisible = ref(false)

// 初始化列显示状态（默认全部显示）
const initColumnVisibility = () => {
  const visibility = {}
  const selected = []

  tableColumns.forEach((column) => {
    visibility[column.prop] = true
    selected.push(column.prop)
  })

  columnVisibility.value = visibility
  selectedColumns.value = selected
}

// 打开列设置弹窗
const openColumnSetting = () => {
  columnSettingVisible.value = true
}

// 保存列设置
const saveColumnSettings = () => {
  const newVisibility = {}

  // 先将所有列设置为隐藏
  tableColumns.forEach((column) => {
    newVisibility[column.prop] = false
  })

  // 再将选中的列设置为显示
  selectedColumns.value.forEach((prop) => {
    newVisibility[prop] = true
  })

  columnVisibility.value = newVisibility
  columnSettingVisible.value = false
}

/** 初始化 **/
onMounted(() => {
  initColumnVisibility()
  getList()
  getUserList()
})

const tableRowClassName = ({ row }) => {
  if (row.markStatus === 1) return 'row-first' // 第1行
  return ''
}
</script>

<style scoped>
:deep(.el-table__row.row-first) {
  background-color: #f26a6e !important;
}

/* 列设置弹窗样式 */
.column-setting-group {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 10px;
}

:deep(.column-setting-group .el-checkbox) {
  display: block;
  margin-bottom: 10px;
}
</style>
